#include "my_thread.h"

#include <chrono>
#include <iostream>
#include <string>

namespace MyTest {
static void worker_function() {
  std::this_thread::sleep_for(std::chrono::milliseconds(100));
  std::cout << "Thread ID: " << std::this_thread::get_id() << " is working." << std::endl;
}
}  // namespace MyTest

int32_t main() {
  int32_t main_res{0};

  try {
    const uint32_t num_threads = 4;

    cpu_set_t cpuset1;
    CPU_ZERO(&cpuset1);
    CPU_SET(0, &cpuset1);

    std::vector<std::shared_ptr<MyTest::MyThread>> test_threads;
    uint32_t thread_idx = 0;
    for (; thread_idx < num_threads; ++thread_idx) {
      const std::string thread_name1 = std::string("Thread_") + std::to_string(thread_idx);
      const std::shared_ptr<MyTest::MyThread> my_t = std::make_shared<MyTest::MyThread>(
          thread_name1, 1, 1, MyTest::worker_function, sizeof(cpuset1), &cpuset1);
      test_threads.push_back(my_t);
    }

    for (const auto& my_t : test_threads) {
      my_t->thread_start();
    }

    std::this_thread::sleep_for(std::chrono::seconds(2));

    for (const auto& my_t : test_threads) {
      my_t->thread_shutdown();
    }
    for (const auto& my_t : test_threads) {
      while (!my_t->has_shutdown()) {
        // std::this_thread::yield();
        my_t->timed_wait(100);
      }
    }
    std::cout << "All threads have been shutdown." << std::endl;
  } catch (...) {
    std::cerr << "Exception occurred" << std::endl;
    main_res = 1;
  }
  return main_res;
}
